import sys

sys.path.append('.')

import os
import tempfile

import pytest

from datetime import datetime

from flaskr import create_app
from flaskr.models import db, Users, Posts


@pytest.fixture
def app():
    """Create and configure a new app instance for each test."""
    # create a temporary file to isolate the database for each test
    db_fd, db_path = tempfile.mkstemp()
    # create the app with common test config
    app = create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///" + db_path})

    # create the database and load test data
    with app.app_context():
        db.create_all()
        user_test = Users(
            username='test',
            password='pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f',
        )
        user_other = Users(
            username='other',
            password='pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79',
        )
        post = Posts(
            author_id=1,
            created=datetime.strptime('2018-01-01 00:00:00', '%Y-%m-%d %H:%M:%S'),
            title='test title',
            body='test\nbody',
        )
        db.session.add_all([user_test, user_other, post])
        db.session.commit()

    yield app

    # close and remove the temporary database
    os.close(db_fd)
    # os.unlink(db_path)


@pytest.fixture
def client(app):
    """A test client for the app."""
    return app.test_client()


@pytest.fixture
def runner(app):
    """A test runner for the app's Click commands."""
    return app.test_cli_runner()


class AuthActions:
    def __init__(self, client):
        self._client = client

    def login(self, username="test", password="test"):
        return self._client.post(
            "/auth/login", data={"username": username, "password": password}
        )

    def logout(self):
        return self._client.get("/auth/logout")


@pytest.fixture
def auth(client):
    return AuthActions(client)
